package com.gqr.jmm;

import java.util.concurrent.CountDownLatch;

/**
 * Copyright (C), 2020-2024,gqr
 * FileName:OutOfOrderExecution
 * author:guqingrong
 * Date:2024-05-01 17:07
 * Description: 演示重排序的现象 "直到达到某个条件才停止"
 * History:
 * <author>    <time>    <version>    <desc>
 * 作者姓名     修改时间     版本号        描述
 */
public class OutOfOrderExecution {
    private volatile static int x = 0, y = 0;
    private volatile static int a = 0, b = 0;

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        for (; ; ) {
            i++;
            x = 0;
            y = 0;
            a = 0;
            b = 0;
            CountDownLatch latch = new CountDownLatch(1);
            Thread one = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        latch.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    a = 1;
                    x = b;
                }
            });

            Thread two = new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        latch.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    b = 1;
                    y = a;
                }
            });
            two.start();
            one.start();
            latch.countDown();
            one.join();
            two.join();
            String result = "第"+i+"次("+x+","+y+")";
            // x == 0 && y == 0  不会再出现过这种结果
            if (x == 1 && y == 1) {
                System.out.println(result);
                break;
            }else{
                System.out.println(result);

            }
        }

    }
}
